<template>
  <div>
    <div style="background: #fff">
      <div id="yuannei" ref="print" style="background: #fff">
        <el-form ref="addform" :model="addform" :rules="rules" class="demo-addform" label-position="top">
          <el-row class="form_item_row" type="flex" justify="space-between">
            <el-col class="form_item_col" :span="7">
              <el-form-item label="外出时间" prop="beginDate" style="margin-bottom: 0">
                <el-date-picker placeholder="请选择外出时间" :disabled="isView" v-model="addform.beginDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 100%">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col class="form_item_col" :span="7">
              <el-form-item label="外出结束时间" prop="beginDate" style="margin-bottom: 0">
                <!-- <el-date-picker
                  placeholder="请选择外出结束时间"
                  :disabled="isView"
                  v-model="addform.endDate"
                  type="datetime"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :picker-options="pickerOptionsEnd"
                  style="width: 100%"
                >
                </el-date-picker> -->
                <el-time-picker
                  is-range
                  :disabled="isView"
                  v-model="addform.endDate"
                  format="HH:mm"
                  value-format="HH:mm"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  placeholder="选择时间范围"
                >
                </el-time-picker>
              </el-form-item>
            </el-col>
            <el-col class="form_item_col" :span="7">
              <el-form-item label="外出时长" prop="hours" style="margin-bottom: 0">
                <el-input v-model="addform.hours" oninput="this.value=this.value.replace(/[^\d.]/g,'');" placeholder="请填写外出时长" :disabled="isView"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="form_item_row" type="flex" justify="space-between">
            <el-col class="form_item_col" :span="7">
              <el-form-item label="测站类型" prop="stType" style="margin-bottom: 0">
                <el-select v-model="addform.stType" filterable placeholder="请选择" :disabled="isView" @change="typeChange">
                  <el-option v-for="item in stTypeList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col class="form_item_col" :span="7">
              <el-form-item label="测站" prop="stnm" style="margin-bottom: 0">
                <el-select v-model="addform.stnm" filterable placeholder="请选择" :disabled="isView" @change="stcdChange">
                  <el-option v-for="item in stationData" :key="item.stnm" :label="item.stnm" :value="item.stnm"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col class="form_item_col" :span="7">
              <el-form-item label="地点" prop="location" style="margin-bottom: 0">
                <el-input v-model="addform.location" placeholder="请填写地点" :disabled="isView"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col class="form_item_col" :span="24">
              <el-form-item label="外出事由" prop="reason" style="margin-bottom: 0">
                <el-input rows="2" type="textarea" :disabled="isView" v-model="addform.reason" placeholder="请填写外出事由"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col class="form_item_col" :span="24">
              <el-form-item label="备注" prop="remark" style="margin-bottom: 0">
                <el-input rows="2" type="textarea" :disabled="isView" v-model="addform.remark" placeholder="请填写备注"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-col class="form_item_col" :span="7">
            <el-form-item label="附件" prop="files" style="margin-bottom: 0">
              <uploadFiles :disabled="isView" title="添加附件" @onImagesChange="handleGetUploadFiles($event, 'files')" ref="upload" :source="source"></uploadFiles>
              <span v-if="!addform.files && isView" style="margin-left: 10px">无附件</span>
            </el-form-item>
          </el-col>
          <el-row>
            <el-col class="form_item_col" :span="24" v-if="query.type == 'shenpi'">
              <el-form-item label="审批意见" prop="remark" style="margin-bottom: 0">
                <el-input rows="2" type="textarea" v-model="approveContent" placeholder="请填写审批意见"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-row class="btn_groups" type="flex" justify="center" v-if="!isView">
          <el-button type="primary" class="search-btn" @click="submitApply('addform', 1)">保存</el-button>
          <el-button type="primary" @click="submitApply('addform', 2)">提交</el-button>
        </el-row>
        <el-row class="btn_groups" type="flex" justify="center" v-if="query.type == 'shenpi'">
          <el-button type="primary" class="table-btn-delete" @click="handleSure(0)">驳回</el-button>
          <el-button type="primary" @click="handleSure(1)">通过</el-button>
        </el-row>
      </div>
    </div>
  </div>
</template>
<script>
import uploadFiles from '../tripManagement/uploadFiles.vue';
import { viewPageStationInfo, saveOutApply, outsidedoApprove } from '../../../api/index';
const createData = () => ({
  beginDate: '', //开始时间
  endDate: '', //结束时间
  files: '', //附件
  fileName: '', //文件名称
  hours: '', //外出时长
  id: '', //主键id
  location: '', //地点
  reason: '', //外出事由
  remark: '', //备注
  stcd: JSON.parse(sessionStorage.getItem('userInfo')).stcdList[0].stcd, //站点编号
  stnm: JSON.parse(sessionStorage.getItem('userInfo')).stcdList[0].stnm, //站点名称
  stType: 1, //测站类型（1坡面径流场，2小流域控制站）
  submitFlag: '', //提交标识（如果新增时提交标识为true，则状态直接改为待审批）
  userCode: JSON.parse(sessionStorage.getItem('userInfo')).userNo //用户编号
});
export default {
  components: { uploadFiles },
  props: {
    query: {
      default: () => ({})
    }
  },
  data() {
    return {
      addform: createData(),
      approveform: {},
      levelType: [],
      type: 'add',
      isView: false,
      isEdit: false,
      rules: {
        beginDate: [{ required: true, message: '必填项', trigger: 'blur' }],
        endDate: [{ required: true, message: '必填项', trigger: 'blur' }],
        stnm: [{ required: true, message: '必填项', trigger: 'blur' }],
        location: [{ required: true, message: '必填项', trigger: 'blur' }],
        hours: [{ required: true, message: '必填项', trigger: 'blur' }],
        reason: [{ required: true, message: '必填项', trigger: 'change' }]
      },
      pickerOptionsStart: {
        disabledDate: (time) => {
          const endDateVal = new Date(this.addform.endDate).getTime();
          if (endDateVal) {
            return time.getTime() > endDateVal - 0;
          }
        }
      },
      pickerOptionsEnd: {
        disabledDate: (time) => {
          const beginDateVal = new Date(this.addform.beginDate).getTime();
          if (beginDateVal) {
            return time.getTime() < beginDateVal - 0;
          }
        }
      },
      stationData: [],
      stTypeList: [
        { label: '坡面径流场', value: 1 },
        { label: '小流域控制站', value: 2 }
      ],
      approveContent: '', //审核意见
      source: []
    };
  },
  created() {
    if (this.query.type == 'view' || this.query.type == 'shenpi') {
      this.isView = true;
    } else {
      this.isView = false;
    }
    switch (this.query.type) {
      case 'add': {
        break;
      }
      case 'edit': {
        this.fetch(this.query);
        break;
      }
      case 'view': {
        this.fetch(this.query);
        break;
      }
      case 'shenpi': {
        this.fetch(this.query);
        break;
      }
    }
    this.getstationData();
  },
  methods: {
    stcdChange() {
      let data = this.stationData.filter((item) => {
        return item.stnm === this.addform.stnm;
      })[0];
      this.addform.stcd = data.stcd;
    },
    fetch(row) {
      let _this = this;
      let addform = JSON.parse(JSON.stringify(row));
      addform.beginDate = row.beginDate.split(' ')[0];
      addform.endDate = [row.beginDate.split(' ')[1], row.endDate.split(' ')[1]];
      this.addform = addform;
      // 设置初始数据
      if (_this.addform.files) {
        const fileName = _this.addform.fileName ? _this.addform.fileName.split('#') : [];
        const source = _this.addform.files.split(',').map((url, index) => {
          return {
            name: fileName[index],
            url: url,
            fileName: fileName[index].slice(0, fileName[index].lastIndexOf('.')),
            type: fileName[index].split('.')[fileName[index].split('.').length - 1]
          };
        });
        this.source = [...source];
      }
    },
    // 上传列表
    handleGetUploadFiles(arr, type) {
      this.source = arr;
    },
    getstationData() {
      let data = {
        currentPage: 1,
        pageSize: 1000
      };
      viewPageStationInfo(data).then((res) => {
        this.stationData = res.object.dataList;
      });
    },
    handerClose() {
      this.$emit('close');
    },
    submitApply(formName, val) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addform.leaveDays = this.day;
          let fileName = [];
          let files = [];
          this.source.forEach((item, index) => {
            fileName.push(item.name);
            files.push(item.url);
          });
          this.addform.fileName = fileName.join('#');
          this.addform.files = files.join(',');
          if (val == 2) {
            this.addform.submitFlag = true;
          } else {
            this.addform.submitFlag = false;
          }
          let addform = JSON.parse(JSON.stringify(this.addform));
          addform.beginDate = this.addform.beginDate + ' ' + this.addform.endDate[0];
          addform.endDate = this.addform.beginDate + ' ' + this.addform.endDate[1];
          saveOutApply(addform).then((e) => {
            this.$emit('close');
            this.$message.success('操作成功');
          });
        } else {
          return false;
        }
      });
    },
    //获取当前时间
    formatDate(date) {
      const value = new Date(date);
      const year = value.getFullYear();
      const month = (value.getMonth() + 1).toString().padStart(2, '0');
      const day = value.getDate().toString().padStart(2, '0');
      var hour = value.getHours(); // 时
      hour = hour < 10 ? '0' + hour : hour; // 如果只有一位，则前面补零
      var minute = value.getMinutes(); // 分
      minute = minute < 10 ? '0' + minute : minute; // 如果只有一位，则前面补零
      var second = value.getSeconds(); // 秒
      second = second < 10 ? '0' + second : second; // 如果只有一位，则前面补零
      return `${year}-${month}-${day} ${hour}:${minute}:${second} `;
    },
    //审核出差记录
    handleSure(val) {
      if (!val && this.approveContent === '') {
        return this.$message.error('请填写审核意见');
      }
      let approver = JSON.parse(sessionStorage.getItem('userInfo')).username;
      let approveTime = new Date();
      approveTime = this.formatDate(approveTime);
      let data = {
        approveContent: this.approveContent,
        approveTime: approveTime,
        approveType: '',
        approver: approver,
        id: '',
        relatedNo: this.addform.id,
        status: val
      };
      outsidedoApprove(data).then((res) => {
        if (res.code == 1) {
          this.$emit('close');
          this.$message.success('审核成功');
        } else {
          this.$message.error('系统错误，请联系管理员');
        }
      });
    },
    typeChange() {
      this.addform.stcd = '';
      this.addform.stnm = '';
    }
  }
};
</script>

<style lang="less" scoped>
/deep/.el-input-number .el-input__inner {
  text-align: left;
}

.dialog_filter_row {
  display: flex;
  justify-content: space-between;
}

.dialog_filter_row .el-form-item {
  display: flex;
  flex-direction: column;
  width: 188px;
}

.dialog_filter_row .el-select,
.dialog_filter_row .el-date-editor,
.dialog_filter_row .el-input-group {
  width: unset !important;
}

.form_item_col {
  width: 188px;
}
::v-deep .el-form-item__label {
  margin: 20px 0 10px;
  height: 14px;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #00041a;
  line-height: 14px;
  text-indent: 14px;

  &:before {
    color: #ff4d4f;
    font-size: 14px;
  }
}

.btn_groups {
  margin: 40px 0 0;
  display: flex;
  justify-content: flex-end;
  .el-button {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 87px;
    height: 32px;
    background: #3f8cff;
    border-radius: 2px;
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #ffffff;
  }
}

.date_picker {
  width: 188px;
}

/deep/.btn_groups .search-btn {
  background-color: #fff;
  border: 1px solid #3f8cff;
  color: #3f8cff;
}
/deep/.el-textarea.is-disabled .el-textarea__inner {
  cursor: default;
}

/deep/.el-input.is-disabled .el-input__inner {
  cursor: default;
}
.table-btn-delete {
  background: #ff544e !important;
  border: 1px solid #ff544e !important;
  border-radius: 2px;
  color: #fff !important;
}
</style>